package com.fmi.timedealer.track;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.fmi.timedealer.ActivityItem;
import com.fmi.timedealer.R;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;


public class TrackTimeActivity extends Activity implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2656381010492231734L;
	private IDataManager dbManager = null;
	private String selectedCategory = "";
	private ActivityItem selectedItem = null;
	private final String START_TRACKING = "Start Tracking";
	private final String TRACK_PAST_EVENT = "Track Past Event";
	private final String[] trackOptions = {START_TRACKING, TRACK_PAST_EVENT};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.track_time);
		
		dbManager = new SQLiteDataManager("MyDB", this);
		
		initCategorySpinner();
	}
	
	private void initCategorySpinner() {
		
		List<String> categories = Arrays.asList(dbManager.getCategoriesNames());
		Collections.sort(categories);
		Spinner spinner = (Spinner) findViewById(R.id.category_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
        		android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new OnCategoryItemSelectedListener());
	}
	
	private void initActionSpinner(List<ActivityItem> activityItems, String category) {
		
		List<ActivityItem> filteredItems = filterItems(activityItems, category);
		Collections.sort(filteredItems);
		Spinner actionSpinner = (Spinner) findViewById(R.id.action_spinner);
		@SuppressWarnings({ "rawtypes", "unchecked" })
		ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, filteredItems);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		actionSpinner.setAdapter(adapter);
		actionSpinner.setClickable(true);
		actionSpinner.setOnItemSelectedListener(new OnActionItemSelectedListener());
	}

	
	private List<ActivityItem> filterItems(List<ActivityItem> activityItems, String category) {

		List<ActivityItem> filtered = new ArrayList<ActivityItem>();
		filtered.add(new ActivityItem("", "", ""));
		
		for (ActivityItem item : activityItems) {
			if (category.equals(item.getCategory())) {
				filtered.add(item);
			}
		}
		return filtered;
	}


	/**
	 * Custom onItemSelectedListener that handles the selection of items
	 * in the category name spinner. Takes care of knowing which category name is selected
	 * and updating the action name spinner with the correct actions
	 */
    public class OnCategoryItemSelectedListener implements OnItemSelectedListener {    

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {  
			selectedCategory = parent.getItemAtPosition(pos).toString();
			//TODO make the search criteria search by category instead of getting all items
			if (selectedCategory != "") {
				List<ActivityItem> activityItems = dbManager.getAllActivities();
				initActionSpinner(activityItems, selectedCategory);
			}
		}   
		
		public void onNothingSelected(AdapterView<?> parent) {    
			// Do nothing.    
		}
	}
    
    /**
	 * Custom onItemSelectedListener that handles the selection of items
	 * in the action name spinner.
	 */
    public class OnActionItemSelectedListener implements OnItemSelectedListener {    

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {  
			selectedItem = (ActivityItem)parent.getItemAtPosition(pos);
			if (selectedItem != null && selectedItem.getName() != "") {
				showTrackOptions();
			}
		}   
		
		public void onNothingSelected(AdapterView<?> parent) {    
			// Do nothing.    
		}
	}
    
    private void showTrackOptions() {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Choose wisely");
    	builder.setItems(trackOptions, new DialogInterface.OnClickListener() {    
    		public void onClick(DialogInterface dialog, int item) {
    			if (trackOptions[item] == START_TRACKING) {
    				if (!dbManager.isActivityRunning(selectedItem)) {
	    				boolean success = dbManager.trackTime(selectedItem, new Date(), null);
	    				if (success) {
	    					Toast.makeText(getApplicationContext(), "Successfully started tracking time for action "
	    										+ selectedItem.getName(), Toast.LENGTH_SHORT).show();
	    				} else {
	    					Toast.makeText(getApplicationContext(), "Failed to start tracking time for action "
									+ selectedItem.getName(), Toast.LENGTH_SHORT).show();
	    				}
    				} else {
    					Toast.makeText(getApplicationContext(), "Selected action is already running: "
								+ selectedItem.getName(), Toast.LENGTH_SHORT).show();
    				}
    				closeActivity();
    			} else if (trackOptions[item] == TRACK_PAST_EVENT) {
    				Intent i = new Intent(TrackTimeActivity.this, TrackPastEventActivity.class);
    				i.putExtra(ActivityItem.ACTIVITY_ITEM, selectedItem);
    				startActivity(i);
    				closeActivity();
    			}
    			    
    		}});
    	AlertDialog trackOptionsDialog = builder.create();
    	trackOptionsDialog.show();
    }
    
    private void closeActivity() {
    	this.finish();
    }
}
